<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" @click="handleDelete" >批量发布</el-button>
        <el-dropdown>
          <el-button type="success" style="margin: 0 10px;">
            批量修改双规格数据<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item>批量选择双规格数据</el-dropdown-item>
            <el-dropdown-item>自动解析双规格数据</el-dropdown-item>
            <el-dropdown-item>通过Excel表格配置双规格数据</el-dropdown-item>
            <el-dropdown-item>自定义双规格套餐</el-dropdown-item>
            <el-dropdown-item>清除选中系列的双规格数据</el-dropdown-item>
            <el-dropdown-item>批量替换规格名称</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>

        <el-button type="danger" @click="handleDelete" >批量删除</el-button>
        <el-button type="info" @click="handleDelete" >删除所有已失效的数据</el-button>

        <el-input v-model="queryParams.productNum" placeholder="请输入搜索内容" prefix-icon="el-icon-search" clearable
          style="width: 240px; margin-left: 10px;" @keyup.enter.native="handleQuery" />
      </el-col>

    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column label="编号" align="center" prop="id" width="180" />
      <el-table-column label="系列名称" align="center" prop="seriesName" />
      <el-table-column label="产品类型" align="center" prop="productType" width="180" :formatter="productTypeFormat"
        :show-overflow-tooltip="true" />
      <el-table-column label="数量" align="center" prop="count" width="180" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="数据状态 (说明)" align="center" prop="status" width="180" :formatter="statusFormat" />
      <el-table-column label="数据容量(MB)" align="center" prop="dataSize" width="180" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="450">
        <template slot-scope="scope">
          <el-button type="success" plain @click="handleUpdate(scope.row)">发布所有产品</el-button>
          <el-button type="info" plain @click="handleGetInfo(scope.row)">查看/调整产品数据 </el-button>
          <el-dropdown @command="(command) => handleCommand(command, scope.row)">
            <el-button type="primary" style="margin: 0 10px;">
              更多操作<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="prolong">延长失效时间</el-dropdown-item>
              <el-dropdown-item command="copy">生成副本</el-dropdown-item>
              <el-dropdown-item command="delete">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <!-- <el-button type="danger"  plain @click="handleDelete(scope.row)"
            v-hasPermi="['product:productInfo:remove']">删除</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.currentPage"
      :limit.sync="queryParams.pageSize" @pagination="getProductList" />

    <releaseDialog v-if="releaseVisible" :releaseItem="releaseItem" @close="closeRelease" />


    <drawerDialog v-if="drawerVisible" :drawerItem="drawerItem" @close="closeDrawer" />



  </div>
</template>

<script>
import {
  productList,
  getProductInfo,
  delProductInfo,
  addProductInfo,
  updateProductInfo,
  queryRepositoryList,
  prolongExpireTime,
  copySeries,
  deleteRepository
} from "@/api/product/productInfo";
import { getToken } from "@/utils/auth";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import releaseDialog from './components/releaseDialog.vue'
import drawerDialog from './drawer/index.vue'


export default {
  name: "product",
  components: { releaseDialog, drawerDialog },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 产品表格数据
      productList: null,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 状态数据字典
      statusOptions: [],
      // 产品类型数据字典
      productTypeOptions: [],
      // 金额类型数据字典
      unitTypeOptions: [],
      // 表单参数
      form: {
      },
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 查询参数
      queryParams: {
        currentPage: 1,
        pageSize: 10,
        productNum: undefined,
        productName: undefined,
        productType: undefined,
        state: undefined,
        tradeFace: undefined
      },
      // 表单校验
      rules: {
        productNum: [
          { required: true, message: "产品编码不能为空", trigger: "blur" },
        ],
        productName: [
          { required: true, message: "产品名称不能为空", trigger: "blur" },
        ],
        productType: [
          { required: true, message: "产品类型不能为空", trigger: "blur" },
        ],
        tradeFace: [
          {
            required: true,
            message: "请输入产品金额",
            trigger: "change"
          },
          {
            pattern: /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/,
            message: "请输入合法的金额数字，最多两位小数",
            trigger: "change"
          }
        ],
        unit: [
          { required: true, message: "金额单位不能为空", trigger: "blur" },
        ],
      },
      show: false,
      releaseVisible: false,
      drawerVisible: false,
      releaseItem: null,
      drawerItem: null
    };
  },

  created() {
    this.getProductList();
    this.getDicts("product_status").then((response) => {
      this.statusOptions = response.data;
    });
    this.getDicts("product_type").then((response) => {
      this.productTypeOptions = response.data;
    });
    this.getDicts("unit_type").then((response) => {
      this.unitTypeOptions = response.data;
    });
  },
  methods: {
    /** 查询产品列表 */
    getProductList() {
      this.loading = true;

      queryRepositoryList(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.loading = false;
        this.productList = response.value.list;
        this.total = response.value.total;
      }).catch(err => {
        this.loading = false;
      })
      // productList(this.addDateRange(this.queryParams, this.dateRange)).then(
      //   (response) => {
      //     this.productList = response.rows;
      //     this.total = response.total;
      //     this.loading = false;
      //   }
      // );
    },
    // 产品状态修改
    handleStatusChange(row) {
      let text = row.state === 0 ? "启用" : "停用";
      this.$confirm(
        '确认要"' + text + '""' + row.productNum + '"产品吗?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return changeProductStatus(row.id, row.state);
        })
        .then(() => {
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.state = row.state == 0 ? 1 : 0;
        });
    },
    closeDrawer() {
      this.drawerVisible = false
    },
    closeRelease() {
      this.releaseVisible = false
    },
    getProductType(row) {
      return this.selectDictLabel(this.statusOptions, row.state);
    },
    // 产品状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 产品类型字典翻译
    productTypeFormat(row, column) {
      return this.selectDictLabel(this.productTypeOptions, row.productType);
    },
    // 金额类型字典防疫
    unitTypeFormat(row, column) {
      return this.selectDictLabel(this.unitTypeOptions, row.unit);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        productNum: undefined,
        productType: undefined,
        tradeFace: undefined,
        state: '0',
        unit: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.getProductList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加产品";
    },
    // 查看按钮
    handleGetInfo(row) {
      this.drawerItem = row
      this.drawerVisible = true
    },
    /** 发布按钮 */
    handleUpdate(row) {
      this.releaseItem = row
      this.releaseVisible = true
      // this.reset();
      // const id = row.id || this.ids;
      // getProductInfo(id).then((response) => {
      //   this.form = response.data;
      //   this.form.state = this.form.state + '';
      //   this.form.state = this.form.state == null ? "" : this.form.state + '';
      //   this.form.productType = this.form.productType == null ? "" : this.form.productType + '';
      //   this.form.unit = this.form.unit == null ? "" : this.form.unit + '';
      //   this.form.tradeFace = this.form.tradeFace == null ? "" : this.form.tradeFace + '';
      //   this.open = true;
      //   this.title = "修改产品";
      // });
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            updateProductInfo(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getProductList();
              }
            });
          } else {
            addProductInfo(this.form).then((response) => {
              console.log(response)
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getProductList();
              }
            });
          }
        }
      });
    },
    handleCommand(command, row) {
      if (command == 'prolong') {
        this.handleProlong(row.id)
      }
      if (command == 'copy') {
        this.handleCopy(row.id, row.count)
      }
      if (command == 'delete') {
        this.deleteRepository(row.id)
      }
    },
    // 延长失效时间
    handleProlong(id) {
      prolongExpireTime(id).then(res => {
        this.getProductList();
        this.$message.success('操作成功')
      })
    },
    // 生成副本
    handleCopy(id, count) {
      copySeries(id, 1).then(res => {
        this.$message.success('操作成功')
        this.getProductList();
      })
    },

    deleteRepository(id) {
      this.$confirm(
        '是否删除当前数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).then(() => {
        deleteRepository(id).then(res => {
          this.$message.success('操作成功')
          this.getProductList();
        })
      })

    },

    /** 删除按钮操作 */
    handleDelete(row) {
      const productIds = row.id || this.ids;
      this.$confirm(
        '是否确认删除待发布编码为"' + productIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return deleteRepository(productIds);
        })
        .then(() => {
          this.getProductList();
          this.msgSuccess("删除成功");
        })
        .catch(function () { });
    },
  },
};
</script>